// 与路由直接关联
import { registerMicroApps, start, addGlobalUncaughtErrorHandler } from 'qiankun'
import apps from './app'
import { listApp } from '@/api/system/app'
import store from '../store'
import { Message } from 'element-ui'
import { action } from '@/micro/action'
  /**
   *  name: 微应用名称
   *  entry: 微应用入口，一般是微应用启动后的地址
   *  container: 微应用挂载节点，类似iframe的id
   *  activeRule: 微应用触发的路由规则 - 触发路由规则后将加载该微应用
   *
   */

  // function getRoutes(appKey){
  //     if (!appKey) return []
  //     const { allAppInfo } = store.getters
  //     return allAppInfo[appKey] && allAppInfo[azppKey].routes
  //   }
  ; (async function () {
    let microapps = []
    await listApp({ status: 0 }).then(async (res) => {
      await res.forEach((item, index) => {
        let app = {}
        app.name = item.appCode
        if (window.env == 'prod' && item.appIp.indexOf('127.0.0.1') > -1) {
          app.entry = item.appRoute != '/' ? `/${item.appRoute}/` : '/'
        } else {
          app.entry = `//${item.appIp}:${item.appPort}/${item.appRoute}/`
        }
        let base = window.versionType == 'webgate' ? '#' : ''
        app.activeRule = `${base}/${item.appCode}`
        app.container = `#micro-${item.appRoute}`
        // app.props = { getRoutes(app.name) }
        app.props = action
        microapps.push(app)
      })
      store.dispatch('app/setMicroApp', microapps)
    })
    registerMicroApps(microapps, {
      beforeLoad: () => {
        return Promise.resolve()
      },
      afterMount: () => {
        return Promise.resolve()
      },
    })

    addGlobalUncaughtErrorHandler((event) => {
      const { message: msg } = event
      if (msg && msg.includes('died in status LOADING_SOURCE_CODE')) {
        Message.error('请检查应用是否正常运行')
      }
    })
  })()

// 启动主应用
export default start
